<script setup lang="ts">
import StudentGiftAPI from "@/api/student-gift";
import { ref } from "vue";

const queryParams = ref<{
  studentId: number | string;
}>({
  studentId: "",
});

const tableData = ref<any[]>([]);
const total = ref<number>(0);
const pageSize = ref<number>(10);
const currentPage = ref<number>(1);

const fetchData = async (pageNum: number) => {
  try {
    let res;
    if (queryParams.value.studentId) {
      res = await StudentGiftAPI.getExchangeRecords(queryParams.value.studentId);
    } else {
      res = await StudentGiftAPI.getAllExchangeRecords();
    }
    tableData.value = res || [];
    total.value = res || 0;
  } catch (error) {
    console.error("请求失败：", error);
  }
};

const handleQuery = () => {
  currentPage.value = 1;
  fetchData(currentPage.value);
};

const resetQuery = () => {
  queryParams.value.studentId = "";
  fetchData(1);
};

const handlePageChange = (pageNum: number) => {
  fetchData(pageNum);
};

fetchData(1);
</script>

<template>
  <div class="app-container">
    <h2>学生礼物兑换记录</h2>

    <el-form :inline="true" :model="queryParams" label-width="100px">
      <el-form-item label="学生ID">
        <el-input v-model="queryParams.studentId" placeholder="请输入学生ID" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="studentId" label="学生ID" width="100" />
      <el-table-column prop="studentName" label="学生姓名" width="120" />
      <el-table-column prop="giftName" label="礼物名称" width="150" />
      <el-table-column prop="point" label="消耗积分" width="100" />
      <el-table-column prop="receiveName" label="收件人" width="100" />
      <el-table-column prop="receivePhone" label="电话" width="120" />
      <el-table-column prop="address" label="收获地址" width="100" />
      <el-table-column
        :formatter="(row) => new Date(row.createTime).toLocaleString()"
        label="兑换时间"
        width="160"
      /> </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center"
    />
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
